import { observable, action } from 'mobx';
import { Base64 } from 'js-base64'
import { Tools, Toast } from 'weaver-mobile';
import { ListViewPage } from 'weaver-mobile-page';

const initState = {
  loading: false,
  route: '',
  id: '',
  listViewStore: new ListViewPage.Store(),
  current: 1,
};

export default class BaseStore {

  id = initState.id;
  route = initState.route;
  @observable loading = initState.loading;
  @observable listViewStore = initState.listViewStore;
  @observable current = initState.current;

  constructor(options) {
    this.id = options.id || '';
    this.route = options.route || '';
  }

  @action
  setState = (params = {}) => {
    Object.keys(params).forEach(key => {
      this[key] = params[key];
    });
  }

  @action
  clear = () => this.setState(initState)

  @action
  getData = (params = { url: '', params: {} }) => {
    this.loading = true;
    this.listViewStore.setState({loading: true});
    try {
      Tools.callApi({
        ...params,
        params: {
          ...params.params,
          _ec_ismobile: true,
        },
      }).then(action((res) => {
        const { status, tableBean } = res;
        if (status === '1') {
          const current = params.params.current || 1;
          this.current = current;
          const data = tableBean.datas.map(d => ({ ...d, ...(d.content ? { content: Base64.decode(d.content) } : {}) }));
          const newState = {
            loading: false,
            current: current,
            columns: tableBean.columns,
            data: [...(current === 1 ? [] : this.listViewStore.data), ...data],
            isTable: false,
            hasMore: tableBean.total > tableBean.current * tableBean.pageSize,
          };
          this.listViewStore.setState(newState);
          this.listViewStore.updateDataSource();
        }
        this.loading = false;
      }));
    } catch (e) {
      Toast.info(e, 1);
      this.loading = false;
    }
    return this;
  }

}
